package handlers

import (
	"html/template"
	"net/http"
	"path/filepath"

	"homepage-backend/internal/config"
	"homepage-backend/internal/services"
)

// SpiderHandler 处理爬虫页面请求
func SpiderHandler(w http.ResponseWriter, r *http.Request) {
	sites, err := services.LoadSites(config.GlobalConfig.SitesFilePath)
	if err != nil {
		http.Error(w, "Failed to load sites", http.StatusInternalServerError)
		return
	}

	tmpl, err := template.ParseFiles(filepath.Join("templates", "spider_template.html"))
	if err != nil {
		http.Error(w, "Template parsing error", http.StatusInternalServerError)
		return
	}

	data := struct {
		Title       string
		Description string
		Keywords    string
		Sites       interface{}
	}{
		Title:       config.GlobalConfig.PageData.Title,
		Description: config.GlobalConfig.PageData.Description,
		Keywords:    config.GlobalConfig.PageData.Keywords,
		Sites:       sites,
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	tmpl.Execute(w, data)
}
